package com.chen.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.servlet.http.HttpServletRequest;

/**
 * @decription:api网关数据校验
 * @atuhor:陈红卫
 * @create : 2017-06-19-9:45
 */
public class AccessFilter extends ZuulFilter {


    private static Logger log= LoggerFactory.getLogger(AccessFilter.class);

    /*
    * 过滤器的类型
    *   pre：表示过滤器在转发之前执行
    * */
    @Override
    public String filterType() {
        return "pre";
    }


    /*
    * 过滤器的执行顺序
    * */
    @Override
    public int filterOrder() {
        return 0;
    }


    /*
    * 过滤器是否应该被执行。一般是通过此函数来指定过滤器的执行范围
    * true表示过滤器执行
    * */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /*
    *
    * */
    @Override
    public Object run() {

        RequestContext ctx=RequestContext.getCurrentContext();
        HttpServletRequest request =ctx.getRequest();
        log.info("send{} request to {} ",request.getMethod(),request.getRequestURI().toString());

        Object accessToken =request.getParameter("accessToken");

        if(accessToken == null)
        {
            log.warn("accesstoke is empty");
            //过来请求，不进行路由
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            return null;
        }

        log.info("access token ok");
        return null;
    }
}
